# -*- coding: utf-8 -*-
import pendulum
from airflow.exceptions import AirflowSkipException
from datetime import timedelta
from airflow.providers.apache.hdfs.sensors.web_hdfs import WebHdfsSensor
from utils.operators.cluster_for_spark_sql_operator  import SparkSqlOperator
from ai_ageing_cusc_hi.dm.complaints_dim_citypair_dt import jms_ai_group__complaints_dim_citypair_dt
from ai_ageing_cusc_hi.dm.complaints_dim_network_dt import jms_ai_group__complaints_dim_network_dt
from ai_ageing_cusc_hi.dm.complaints_dim_receiver_dt import jms_ai_group__complaints_dim_receiver_dt
from ai_ageing_cusc_hi.dm.complaints_dim_sender_dt import jms_ai_group__complaints_dim_sender_dt
from ai_ageing_cusc_hi.dwd.dwd_warhouse.dwd_wide_unsign_summary_waybill_hi import jms_dwd__dwd_wide_unsign_summary_waybill_hi


cst = pendulum.timezone('Asia/Shanghai')
class IndicatorWebHdfsSensor(WebHdfsSensor):
    def pre_execute(self, context):
        day = cst.convert(context['ti'].execution_date) + timedelta(hours=6)

        schedule_date = ['00']

        if day.strftime('%H') in schedule_date:
            print(f'{day.strftime("%H")} in {schedule_date}, should skip')
            super().pre_execute(context)
            raise AirflowSkipException()
        else:
            print(f'{day.strftime("%H")} not in {schedule_date}, run now')
            super().pre_execute(context)


jms_dwd__dwd_tab_barscan_difficult_base_hi = IndicatorWebHdfsSensor(
    pool='unlimited_pool',
    task_id="jms_dwd__dwd_tab_barscan_difficult_base_hi",
    filepath='/dw/hive/jms_dwd.db/external/dwd_tab_barscan_difficult_base_hi/dt={{ execution_date | hour_add(5) | cst_hour }}',
    execution_timeout=timedelta(minutes=15),
    email=['jarl.huang@jtexpress.com','yl_bigdata@yl-scm.com'],
    retries=2,
)

class IndicatorSparkSqlOperator(SparkSqlOperator):
    def pre_execute(self, context):
        day = cst.convert(context['ti'].execution_date) + timedelta(hours=6)

        schedule_date = ['00']

        if day.strftime('%H') in schedule_date:
            print(f'{day.strftime("%H")} in {schedule_date}, should skip')
            super().pre_execute(context)
            raise AirflowSkipException()
        else:
            print(f'{day.strftime("%H")} not in {schedule_date}, run now')
            super().pre_execute(context)

jms_ai_group__dm_complaints_warning_indicator_hi = IndicatorSparkSqlOperator(
    task_id='jms_ai_group__dm_complaints_warning_indicator_hi',
    email=['jarl.huang@jtexpress.com', 'yl_bigdata@yl-scm.com'],
    name='jms_ai_group__dm_complaints_warning_indicator_hi_{{ execution_date | date_add(1) | cst_hour }}',
    email_on_retry=True,
    retries=0,
    sql='ai_ageing_cusc_hi/dm/dm_complaints_warning_indicator_hi/execute.sql',
    yarn_queue='pro',
    driver_memory='4G',
    driver_cores=4,
    executor_memory='16G',
    executor_cores=4,
    pool_slots=2,
    pool='unlimited_pool',
    num_executors=50,  # spark.dynamicAllocation.enabled 为 True 时，num_executors 表示最少 Executor 数
    conf={'spark.executor.memoryOverhead': '5G',
          'spark.dynamicAllocation.enabled': 'true',
          'spark.shuffle.service.enabled': 'true',
          'spark.dynamicAllocation.maxExecutors': 60,
          'spark.sql.sources.partitionOverwriteMode': 'dynamic',
          'spark.dynamicallocation.enabled': 'true',
          'spark.dynamicAllocation.cachedExecutorIdleTimeout': 120,
          'spark.sql.shuffle.partitions': 600,
          'spark.port.maxRetries': 100,
          'spark.locality.wait.node': '100ms',
          'spark.executor.extraJavaOptions': '-XX:+UseG1GC -XX:ParallelGCThreads=6'
          },
    hiveconf={'hive.exec.dynamic.partition': 'true',
              'hive.exec.dynamic.partition.mode': 'nonstrict',
              'hive.exec.max.dynamic.partitions.pernode': 5000,
              'hive.exec.max.dynamic.partitions': 30000
              },
    execution_timeout=timedelta(hours=2),
    priority_weight=20,
)  # type: SparkSqlOperator

jms_ai_group__dm_complaints_warning_indicator_hi << [
    jms_ai_group__complaints_dim_citypair_dt,
    jms_ai_group__complaints_dim_network_dt,
    jms_ai_group__complaints_dim_receiver_dt,
    jms_ai_group__complaints_dim_sender_dt,
    jms_dwd__dwd_wide_unsign_summary_waybill_hi,
    jms_dwd__dwd_tab_barscan_difficult_base_hi
]
